package com.example.user_service.config;


import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import java.util.HashMap;

/*
 *@验证身份信息
 */
@Component
public class Idcred {

    public int yzidcred(String name, String idcred) {
        String url = "https://idcardv2.shumaidata.com/new-idcard";
        String appCode = "f61ee2eeaea548d3b22e4a28e6231378";

        Map<String, String> params = new HashMap<>();
        params.put("idcard", idcred);
        params.put("name", name);

        String result = null;
        try {
            result = get(appCode, url, params);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result);

        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
        String i = data.getString("result");
        return Integer.parseInt(i);
    }


    private String get(String appCode, String url, Map<String, String> params) throws IOException {
        url = url + buildRequestUrl(params);
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).build();
        Response response = client.newCall(request).execute();
        System.out.println("返回状态码" + response.code() + ",message:" + response.message());
        String result = response.body().string();
        return result;
    }

    private String buildRequestUrl(Map<String, String> params) {
        StringBuilder url = new StringBuilder("?");
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            url.append(key).append("=").append(params.get(key)).append("&");
        }
        return url.toString().substring(0, url.length() - 1);
    }


}
